package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.entity.dto.SetmealDto;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.ISetmealDishService;
import com.itheima.reggie.service.ISetmealService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/setmeal")
@RestController
public class SetMealController {

    @Autowired
    private ISetmealService iSetmealService;

    @Autowired
    private ISetmealDishService iSetmealDishService;

    @Autowired
    private ICategoryService iCategoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @CacheEvict(value = "setmeal",allEntries = true)
    public R addSetmeal(@RequestBody SetmealDto setmealDto){

        //1、保存套餐数据到 setmeal表中 ： SetmealMapper
        iSetmealService.save(setmealDto);
        //2、保存套餐菜品数据到 setmeal_dish表中： SetmealDishMapper
        //2.1 获取当前套餐的菜品列表
        List<SetmealDish> list = setmealDto.getSetmealDishes();
        //List<SetmealDto> setmealDtos = new ArrayList<>();
        //2.2 循环遍历，获取每一个套餐菜品数据 setmealDish
        for (SetmealDish dish : list) {
            dish.setSetmealId(setmealDto.getId());

        }
        //2.3 获取套餐id，并set到setmealDish中

        iSetmealDishService.saveBatch(list);
        //2.4 保存套餐菜品数据 setmealDish




        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R selectByPage(Integer page,Integer pageSize,String name){


        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        IPage<Setmeal> page1 = new Page<>(page,pageSize);
        qw.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        qw.orderByDesc(Setmeal::getUpdateTime);
        iSetmealService.page(page1,qw);
        List<Setmeal> records = page1.getRecords();
        long total = page1.getTotal();

        List<SetmealDto> setmealDtos = new ArrayList<>();
        for (Setmeal record : records) {
            Long categoryId = record.getCategoryId();
            Category category = iCategoryService.getById(categoryId);
            String name1 = null;
            if (category!=null) {
                name1 = category.getName();
            }
            SetmealDto setmealDto = new SetmealDto();
            setmealDto.setCategoryName(name1);
            BeanUtils.copyProperties(record,setmealDto);
            setmealDtos.add(setmealDto);

        }

        Map data = new HashMap();
        data.put("total",total);
        data.put("records",setmealDtos);

        return R.success(data);
    }

    @DeleteMapping
    @CacheEvict(value = "setmeal",allEntries = true)
    public R deleteSetmeal(@RequestParam List<String> ids){
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.in(SetmealDish::getSetmealId, ids);
        LambdaQueryWrapper<Setmeal> q = new LambdaQueryWrapper<>();
        q.in(Setmeal::getId,ids);

        List<Setmeal> list = iSetmealService.list(q);
        for (Setmeal setmeal : list) {
            if (setmeal.getStatus()==1){
                return R.error("不允许删除");
            }
            iSetmealDishService.remove(qw);
            iSetmealService.removeByIds(ids);
        }
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmeal",allEntries = true)
    public R updateStatus(@PathVariable Integer status ,@RequestParam List<String> ids){
        LambdaUpdateWrapper<Setmeal> qw = new LambdaUpdateWrapper<>();
        qw.set(Setmeal::getStatus,status);
        qw.in(Setmeal::getId,ids);
        iSetmealService.update(qw);


/*
        LambdaQueryWrapper<Setmeal> q = new LambdaQueryWrapper<>();
        q.in(Setmeal::getId,ids);
        List<Setmeal> list = iSetmealService.list(q);
        for (Setmeal setmeal : list) {


            setmeal.setStatus(status);
        }
        iSetmealService.update(qw);
        iSetmealService.saveBatch(list);
*/

        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R selectById(@PathVariable Long id){

        Setmeal setmeal = iSetmealService.getById(id);
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId,id);

        List<SetmealDish> list = iSetmealDishService.list(qw);

        SetmealDto setmealDto = new SetmealDto();
        setmealDto.setSetmealDishes(list);
        BeanUtils.copyProperties(setmeal,setmealDto);


        return R.success(setmealDto);
    }

    @PutMapping
    @CacheEvict(value = "setmeal",allEntries = true)
    public R updateSetmeal(@RequestBody SetmealDto setmealDto){


        //1、根据id更新 setmeal 套餐表数据 update setmeal set xx=?,.. where id =?


        //2、操作套餐对应的菜品数据： setmeal_dish
        //2.1 先根据套餐id删除套餐对应的菜品数据： delete from setmeal_dish where setmeal_id =?
        // 获取套餐id   setmealDto.getId()
        Long id = setmealDto.getId();
        // 使用 setmealDishMapper 根据套餐id进行删除 ：delete from setmeal_dish where setmeal_id =?
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId,id);
        iSetmealDishService.remove(qw);
        //2.2 重新添加新的套餐对应的菜品数据 insert setmeal_dish values (..)
        // setmealDto.getSetmealDishes() 获取套餐的菜品集合 List<SetmealDish>
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        // 遍历套餐菜品集合数据
       // for (SetmealDish setmealDish : setmealDishes) {
            // 有没有数据需要set ： 设置套餐id  setSetmealId
        for (SetmealDish setmealDish : setmealDishes) {
          setmealDish.setSetmealId(setmealDto.getId());
        }
        iSetmealDishService.saveBatch(setmealDishes);
            // 添加套餐菜品数据 insert
        iSetmealService.updateById(setmealDto);




        return R.success("修改成功");
    }

    @GetMapping("/list")
    @Cacheable(value = "setmeal",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> listSetmel(Setmeal setmeal){



        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(Setmeal::getCategoryId,setmeal.getCategoryId());
        qw.eq(Setmeal::getStatus,setmeal.getStatus());
        List<Setmeal> list = iSetmealService.list(qw);
        return R.success(list);
    }

}
